from flask import Blueprint, request, jsonify, url_for
from app.models.user import User
from app.extensions import db
from app.utils import JwtToken
from app.utils.file_utils import save_avatar
# from app.utils.jwt_token import jwt_tools

user_bp = Blueprint('user_bp', __name__)

@user_bp.route('/api/update-username', methods=['POST'])
def update_username():
    try:
        # 1. 从请求头里拿 Bearer Token
        auth_header = request.headers.get("Authorization", None)
        if not auth_header or not auth_header.startswith("Bearer "):
            return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

        token = auth_header.split(" ")[1]

        # 2. 解析 token 获取 openid
        payload, verify_status = JwtToken.parse_token(token)
        if not verify_status or "openid" not in payload:
            return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

        openid = payload["openid"]

        # 3. 获取参数（新昵称）
        data = request.get_json()
        new_name = data.get("username")

        if not new_name:
            return jsonify({'code': 400, 'msg': '缺少参数 username'}), 400

        # 4. 查找用户
        user = User.query.filter_by(openid=openid).first()
        if not user:
            return jsonify({'code': 404, 'msg': '用户不存在'}), 404

        # 5. 更新昵称
        user.username = new_name
        db.session.commit()

        return jsonify({'code': 200, 'msg': '昵称修改成功', 'username': new_name})

    except Exception as e:
        return jsonify({'code': 500, 'msg': str(e)}), 500


@user_bp.route('/api/upload-avatar', methods=['POST'])
def upload_avatar():
    try:
        # 1. 从请求头里拿 Bearer Token
        auth_header = request.headers.get("Authorization", None)
        if not auth_header or not auth_header.startswith("Bearer "):
            return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

        token = auth_header.split(" ")[1]

        # 2. 解析 token 获取 openid
        payload, verify_status = JwtToken.parse_token(token)
        if not verify_status or "openid" not in payload:
            return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

        openid = payload["openid"]
        file = request.files.get('avatar')

        if not openid or not file:
            return jsonify({'code': 400, 'msg': '缺少参数'}), 400

        user = User.get_user_by_openid(openid)
        if not user:
            return jsonify({'code': 404, 'msg': '用户不存在'}), 404

        # 保存头像图片到服务器，返回路径
        save_path = save_avatar(file, user.id)

        # 存储相对路径
        user.avatar_url = save_path
        db.session.commit()

        return jsonify({'code': 200, 'msg': '上传成功', 'avatar': url_for('static', filename=user.avatar_url, _external=True)})
    except Exception as e:
        return jsonify({'code': 500, 'msg': str(e)}), 500


@user_bp.route('/api/bind-class', methods=['POST'])
def bind_class():
    try:
        # 1. 从请求头里拿 Bearer Token
        auth_header = request.headers.get("Authorization", None)
        if not auth_header or not auth_header.startswith("Bearer "):
            return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

        token = auth_header.split(" ")[1]

        # 2. 解析 token 获取 openid
        payload, verify_status = JwtToken.parse_token(token)
        if not verify_status or "openid" not in payload:
            return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

        openid = payload["openid"]

        # 3. 获取参数（学校和班级）
        data = request.get_json()
        school = data.get("school")
        classname = data.get("classname")

        # if not school or not classname:
        #     return jsonify({'code': 400, 'msg': '缺少参数 school 或 classname'}), 400

        # 4. 查找用户
        user = User.query.filter_by(openid=openid).first()
        if not user:
            return jsonify({'code': 404, 'msg': '用户不存在'}), 404

        # 5. 更新 class_name
        user.school = school
        user.class_name = classname
        db.session.commit()

        return jsonify({'code': 200, 'msg': '班级绑定成功', 'classname': classname})

    except Exception as e:
        return jsonify({'code': 500, 'msg': str(e)}), 500


@user_bp.route('/api/check-school-bound', methods=['GET'])
def check_school_bound():
    try:
        # 1. 从请求头里拿 Bearer Token
        auth_header = request.headers.get("Authorization", None)
        if not auth_header or not auth_header.startswith("Bearer "):
            return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

        token = auth_header.split(" ")[1]

        # 2. 解析 token 获取 openid
        payload, verify_status = JwtToken.parse_token(token)
        if not verify_status or "openid" not in payload:
            return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

        openid = payload["openid"]

        # 3. 查找用户
        user = User.query.filter_by(openid=openid).first()
        if not user:
            return jsonify({'code': 404, 'msg': '用户不存在'}), 404

        # 4. 判断是否绑定学校
        is_bound = bool(user.school and user.class_name)

        return jsonify({
            'code': 200,
            'msg': '查询成功',
            'data': {
                'is_bound': is_bound,
                'school': user.school if user.school else "",
                'class_name': user.class_name if user.class_name else ""
            }
        })

    except Exception as e:
        return jsonify({'code': 500, 'msg': str(e)}), 500
